package com.igoal.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.tuckey.web.filters.urlrewrite.utils.StringUtils;

import com.igoal.entity.Audit;
import com.igoal.entity.DataStatus;

/**
 * This class serves as the Base class for all other DAOs - namely to hold
 * common CRUD methods that they might all use. You should only need to extend
 * this class when your require custom CRUD logic.
 * <p/>
 * <p>
 * To register this class in your Spring context file, use the following XML.
 * 
 * <pre>
 *      &lt;bean id="fooDao" class="org.appfuse.dao.hibernate.GenericDaoHibernate"&gt;
 *          &lt;constructor-arg value="org.appfuse.model.Foo"/&gt;
 *          &lt;property name="sessionFactory" ref="sessionFactory"/&gt;
 *      &lt;/bean&gt;
 * </pre>
 * 
 * @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a>
 * @param <T>
 *            a type variable
 * @param <PK>
 *            the primary key for that type
 */
public class GenericDaoHibernate<T, PK extends Serializable> implements
		GenericDao<T, PK> {
	/**
	 * Log variable for all child classes. Uses LogFactory.getLog(getClass())
	 * from Commons Logging
	 */
	protected final Log log = LogFactory.getLog(getClass());
	private Class<T> persistentClass;
	private HibernateTemplate hibernateTemplate;
	private SessionFactory sessionFactory;

	/**
	 * Constructor that takes in a class to see which type of entity to persist.
	 * Use this constructor when subclassing.
	 * 
	 * @param persistentClass
	 *            the class type you'd like to persist
	 */
	public GenericDaoHibernate(final Class<T> persistentClass) {
		this.persistentClass = persistentClass;
	}

	protected final Session getSession(boolean allowCreate)
			throws DataAccessResourceFailureException, IllegalStateException {

		return (!allowCreate ? SessionFactoryUtils.getSession(
				getSessionFactory(), false) : SessionFactoryUtils.getSession(
				getSessionFactory(),
				this.hibernateTemplate.getEntityInterceptor(),
				this.hibernateTemplate.getJdbcExceptionTranslator()));
	}

	protected final Session getSession()
			throws DataAccessResourceFailureException, IllegalStateException {

		return getSession(this.hibernateTemplate.isAllowCreate());
	}

	/**
	 * Constructor that takes in a class and sessionFactory for easy creation of
	 * DAO.
	 * 
	 * @param persistentClass
	 *            the class type you'd like to persist
	 * @param sessionFactory
	 *            the pre-configured Hibernate SessionFactory
	 */
	public GenericDaoHibernate(final Class<T> persistentClass,
			SessionFactory sessionFactory) {
		this.persistentClass = persistentClass;
		this.sessionFactory = sessionFactory;
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	public HibernateTemplate getHibernateTemplate() {
		return this.hibernateTemplate;
	}

	public SessionFactory getSessionFactory() {
		return this.sessionFactory;
	}

	@Autowired
	@Required
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		return hibernateTemplate.loadAll(this.persistentClass);
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<T> getAllDistinct() {
		Collection result = new LinkedHashSet(getAll());
		return new ArrayList(result);
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public T get(PK id) {
		T entity = (T) hibernateTemplate.get(this.persistentClass, id);

		if (entity == null) {
			log.warn("Uh oh, '" + this.persistentClass + "' object with id '"
					+ id + "' not found...");
			throw new ObjectRetrievalFailureException(this.persistentClass, id);
		}

		return entity;
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public boolean exists(PK id) {
		T entity = (T) hibernateTemplate.get(this.persistentClass, id);
		return entity != null;
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public T save(T object) {
		if (object instanceof Audit) {
			Audit audit = (Audit) object;			
			if(audit.getUpdateDate() == null)
				audit.setUpdateDate(new Date());
		}
		return (T) hibernateTemplate.merge(object);
	}

	/**
	 * {@inheritDoc}
	 */
	public void remove(PK id) {
		hibernateTemplate.delete(this.get(id));
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByNamedQuery(String queryName,
			Map<String, Object> queryParams) {
		String[] params = new String[queryParams.size()];
		Object[] values = new Object[queryParams.size()];

		int index = 0;
		for (String s : queryParams.keySet()) {
			params[index] = s;
			values[index++] = queryParams.get(s);
		}

		return hibernateTemplate.findByNamedQueryAndNamedParam(queryName,
				params, values);
	}

	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(DetachedCriteria dc) {
		return hibernateTemplate.findByCriteria(dc);
	}

	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(DetachedCriteria dc, int firstResult,
			int maxResults) {
		return hibernateTemplate.findByCriteria(dc, firstResult, maxResults);
	}

	protected void getByStatus(DetachedCriteria dc, DataStatus status) {
		dc.add(Restrictions.eq("status", status));
	}
	
	public List<T> pagingDependOnOrderProperty(Map<String, Object> criteria,
			String orderProperty, Object lastOrderPropertyValue,
			boolean before, int numberOfRecord, boolean asc) {
		List<T> result = null;

		DetachedCriteria dc = DetachedCriteria.forClass(persistentClass);

		if(criteria != null){
			Set<String> keys = criteria.keySet();
	
			for (String property : keys) {
				if (hasProperty(property)) {
					Object value = criteria.get(property);
					dc.add(Restrictions.eq(property, value));
				}
			}
		}
		
		if(!StringUtils.isBlank(orderProperty)){
			if(asc){
				dc.addOrder(Order.asc(orderProperty));
			}else{
				dc.addOrder(Order.desc(orderProperty));
			}
			if (lastOrderPropertyValue != null) {
				if (before) {
					dc.add(Restrictions.gt(orderProperty, lastOrderPropertyValue));
				} else {
					dc.add(Restrictions.lt(orderProperty, lastOrderPropertyValue));
				}
			}
		}

		if (numberOfRecord > 0) {
			result = findByCriteria(dc, 0, numberOfRecord);
		} else {
			result = findByCriteria(dc);
		}

		return result;
	}

	public List<T> pagingDependOnOrderProperty(Map<String, Object> criteria,
			String orderProperty, Object lastOrderPropertyValue,
			boolean before, int numberOfRecord) {
		List<T> result = null;

		DetachedCriteria dc = DetachedCriteria.forClass(persistentClass);
		
		if(criteria != null){
			Set<String> keys = criteria.keySet();
	
			for (String property : keys) {
				if (hasProperty(property)) {
					Object value = criteria.get(property);
					dc.add(Restrictions.eq(property, value));
				}
			}
		}
		
		if(!StringUtils.isBlank(orderProperty)){
			dc.addOrder(Order.desc(orderProperty));
			if (lastOrderPropertyValue != null) {
				if (before) {
					dc.add(Restrictions.gt(orderProperty, lastOrderPropertyValue));
				} else {
					dc.add(Restrictions.lt(orderProperty, lastOrderPropertyValue));
				}
			}
		}

		if (numberOfRecord > 0) {
			result = findByCriteria(dc, 0, numberOfRecord);
		} else {
			result = findByCriteria(dc);
		}

		return result;
	}

	private boolean hasProperty(String property) {
		// TODO: check if property belongs to persistent class or not
		return true;
	}

	@SuppressWarnings({ "rawtypes" })
	public int countByCriteria(DetachedCriteria dc) {
		dc.setProjection(Projections.rowCount());
		Criteria c = dc.getExecutableCriteria(getSession());
		Iterator itr = c.list().iterator();
		if (itr.hasNext()) {
			return ((Number) itr.next()).intValue();
		}
		return 0;
	}

	@SuppressWarnings({ "rawtypes" })
	public int countAll() {
		DetachedCriteria dc = DetachedCriteria.forClass(persistentClass);
		dc.setProjection(Projections.rowCount());
		Criteria c = dc.getExecutableCriteria(getSession());
		Iterator itr = c.list().iterator();
		if (itr.hasNext()) {
			return ((Number) itr.next()).intValue();
		}
		return 0;
	}

	@SuppressWarnings("rawtypes")
	public Object findMax(String propertyName, DetachedCriteria dc) {
		if (dc == null) {
			dc = DetachedCriteria.forClass(persistentClass);
		}
		dc.setProjection(Projections.max(propertyName));
		Criteria c = dc.getExecutableCriteria(getSession());
		Iterator itr = c.list().iterator();
		if (itr.hasNext()) {
			return itr.next();
		}
		return null;
	}

	protected void getRandomEntities(DetachedCriteria dc) {
		dc.add(Restrictions.sqlRestriction("1=1 order by rand()"));
	}

	public Map<Integer, Object> countPage(Map<String, Object> criteria, String orderProperty, int numberOfRecord) {
		DetachedCriteria dc = DetachedCriteria.forClass(persistentClass);
		
		Set<String> keys = criteria.keySet();

		for (String property : keys) {
			if (hasProperty(property)) {
				Object value = criteria.get(property);
				dc.add(Restrictions.eq(property, value));
			}
		}

		dc.addOrder(Order.desc(orderProperty));
		
		return countPage(dc, orderProperty, numberOfRecord);
	}

	public Map<Integer, Object> countPage(DetachedCriteria dc, String orderProperty,
			int numberOfRecord) {
		if(dc == null){
			return null;
		}
		
		int totalRecords = countByCriteria(dc);
		if(totalRecords <= 0){
			return null;
		}
		
		Map<Integer, Object> pages = new HashMap<Integer, Object>();
		
		if(numberOfRecord <= 0){
			numberOfRecord = 1;
		}
		
		int evenPages = totalRecords / numberOfRecord;
		boolean hasOddPages = totalRecords % numberOfRecord > 0;
		
		if(hasOddPages){
			++evenPages;
		}
		
		for(int index=1; index<=evenPages; index++){
			int fristRecord = index*numberOfRecord;
			List<T> list = null;			
			try{
				list = findByCriteria(dc, fristRecord+numberOfRecord-1, 1);				
			}catch (Exception e) {				
				list = null;
			}
			
			if(list == null || list.isEmpty()){
				try{
					list = findByCriteria(dc, fristRecord, numberOfRecord);
				}catch (Exception e) {
					list = new ArrayList<T>();
				}
			}
			
			if(!list.isEmpty()){
				int lastItemIndex = list.size();
				T entity = list.get(lastItemIndex);
				try{
					BeanWrapper bw = new BeanWrapperImpl(entity);
					Object orderValue = bw.getPropertyValue(orderProperty);
					pages.put(index, orderValue);			
				}catch (Exception e) {
					
				}
			}
		}
		
		return pages;
	}

	public Map<Integer, Object> countPageWithDefaultCriteria(int numberOfRecord) {
		String defaultOrderProperty = "createDate";
		
		DetachedCriteria dc = DetachedCriteria.forClass(persistentClass);
		dc.addOrder(Order.desc(defaultOrderProperty));
		
		return countPage(dc, defaultOrderProperty, numberOfRecord);
	}

	public void deleteAll(Collection<T> entities) {
		getHibernateTemplate().deleteAll(entities);
	}

}
